<!DOCTYPE html>
<html>
<head>
    <title>文件服务器</title>
    <style>
        body { max-width: 800px; margin: 20px auto; padding: 20px; }
        .file-item { padding: 8px; border-bottom: 1px solid #eee; }
        .download-btn { float: right; }
    </style>
</head>
<body>
<h1>文件上传</h1>
<form id="uploadForm" enctype="multipart/form-data">
    <input type="file" name="file" id="fileInput" required>
    <button type="submit">上传文件</button>
</form>

<h2>文件列表</h2>
<div id="fileList"></div>

<script>
    // 动态加载文件列表
    async function refreshFileList() {
        try {
            const response = await fetch('/files');
            const files = await response.json();

            const listHtml = files.map(file => `
                    <div class="file-item">
                        ${file}
                        <button class="download-btn"
                                onclick="downloadFile('${file}')">
                            下载
                        </button>
                    </div>
                `).join('');

            document.getElementById('fileList').innerHTML = listHtml;
        } catch (error) {
            console.error('加载文件列表失败:', error);
        }
    }

    // 文件下载函数
    function downloadFile(filename) {
        window.open(`/download/${encodeURIComponent(filename)}`, '_blank');
    }

    // 表单提交处理
    document.getElementById('uploadForm').addEventListener('submit', async (e) => {
        e.preventDefault();

        const formData = new FormData();
        formData.append('file', document.getElementById('fileInput').files[0]);

        try {
            const response = await fetch('/upload', {
                method: 'POST',
                body: formData
            });

            if (response.ok) {
                alert('上传成功！');
                document.getElementById('fileInput').value = '';
                refreshFileList();
            } else {
                alert(`上传失败: ${await response.text()}`);
            }
        } catch (error) {
            alert('上传请求失败: ' + error.message);
        }
    });

    // 初始化加载
    refreshFileList();
</script>
</body>
</html>